package com.hyc.myvideo.ui.service;

import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Binder;
import android.os.Handler;
import android.os.IBinder;
import android.support.annotation.IntDef;
import android.support.annotation.Nullable;
import com.hyc.myvideo.data.api.model.CurriculumHour;
import com.hyc.myvideo.ui.view.Notifier;
import com.hyc.myvideo.utils.PlayerUtils;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import timber.log.Timber;

/**
 * 音频播放后台
 * Created by dfeads on 2017/7/18.
 */

public class AudioService extends Service {
  private final static int STATE_IDLE=0x7771;
  private final static int STATE_PREPARING=0x7772;
  private final static int STATE_PLAYING=0x7773;
  private final static int STATE_PAUSE=0x7774;

  private int mPlayState = STATE_IDLE;

  private MediaPlayer mPlayer;
  private List<CurriculumHour> curriculumHourList = null;
  private int mPosition = 0;
  /** 循环 */
  private boolean isLoop = true;

  private Handler mHandler = new Handler();

  private OnAudioEventListener onAudioEventListener;

  public void setOnAudioEventListener(OnAudioEventListener onAudioEventListener) {
    this.onAudioEventListener = onAudioEventListener;
  }

  public int getTotalTime() {
    return mPlayer.getDuration();
  }

  public boolean isPlaying() {
    return mPlayer.isPlaying();
  }

  public void setCurriculumHourList(List<CurriculumHour> curriculumHourList) {
    this.curriculumHourList.clear();
    this.curriculumHourList.addAll(curriculumHourList);
  }

  @Nullable @Override public IBinder onBind(Intent intent) {
    Timber.e("=========onBind===========");
    return new AudioBinder();
  }

  @Override public void onCreate() {
    super.onCreate();
    curriculumHourList = new ArrayList<>();
    mPlayer = new MediaPlayer();
    mPlayer.setOnCompletionListener(completionListener);
    Notifier.init(this);
  }

  //第一次播放
  public void play(CurriculumHour curriculumHour) {
    try {
      mPlayer.reset();
      mPlayer.setDataSource(curriculumHour.getCurriculum_hour_url());
      Timber.e("''''setDataSource''''''");
      //mPlayer.setDataSource("http://fs.web.kugou.com/e762ed8f14b6778ed89a970894f74e72/598acb82/G112/M0B/02/04/UJQEAFmIOBCAV4B1AERGZUkCi4U943.mp3");
      mPlayer.setOnPreparedListener(preparedListener);
      mPlayer.prepareAsync();
      mPlayer.setOnBufferingUpdateListener(bufferingUpdateListener);
      Notifier.showPlay(curriculumHour);
    } catch (IOException e) {
      e.printStackTrace();
    }
  }

  public void play(int position) {
    if (position < 0) {
      position = curriculumHourList.size() - 1;
    } else if (position >= curriculumHourList.size()) {
      position = 0;
    }
    mPosition = position;
    play(curriculumHourList.get(position));
  }

  /**
   * 播放/暂停
   */
  public void playPause() {
    if (isPlaying()) {
      mPlayer.pause();
      mHandler.removeCallbacks(mPublishRunnable);
    } else {
      start();
    }
  }

  /**
   * 下一首
   */
  public void next() {
    play(mPosition + 1);
  }

  /**
   * 上一首
   */
  public void pre() {
    play(mPosition - 1);
  }

  private void start() {
    mPlayer.start();
    mPlayState=STATE_PLAYING;
    mHandler.post(mPublishRunnable);
  }

  public void seekTo(int progress) {
    if (isPlaying() && onAudioEventListener != null) {
      mPlayer.seekTo(progress);
      //onAudioEventListener.onPublish(progress);
    }
  }

  MediaPlayer.OnBufferingUpdateListener bufferingUpdateListener =
      new MediaPlayer.OnBufferingUpdateListener() {
        @Override public void onBufferingUpdate(MediaPlayer mediaPlayer, int percent) {
          if (percent >= 0 && percent <= 100 && onAudioEventListener != null) {
            int secondProgress = mediaPlayer.getDuration() * percent / 100;
            onAudioEventListener.onBufferingUpdate(secondProgress);
            Timber.e("====onBufferingUpdate===" + percent);
          }
        }
      };

  MediaPlayer.OnPreparedListener preparedListener = new MediaPlayer.OnPreparedListener() {
    @Override public void onPrepared(MediaPlayer mediaPlayer) {
      if (onAudioEventListener != null) {
        onAudioEventListener.onMaxPro(mediaPlayer.getDuration());
      }
      mPlayState=STATE_PREPARING;
      start();
      Timber.e(PlayerUtils.converLongTimeToStr(mediaPlayer.getCurrentPosition())
          + "==mediaPlayer=="
          + PlayerUtils.converLongTimeToStr(mediaPlayer.getDuration()));
    }
  };

  MediaPlayer.OnCompletionListener completionListener = new MediaPlayer.OnCompletionListener() {
    @Override public void onCompletion(MediaPlayer mediaPlayer) {

    }
  };

  private Runnable mPublishRunnable = new Runnable() {
    @Override public void run() {
      if (isPlaying() && onAudioEventListener != null) {
        onAudioEventListener.onPublish(mPlayer.getCurrentPosition());
      }
      mHandler.postDelayed(this, 100l);
    }
  };

  public class AudioBinder extends Binder {

    public AudioService getService() {
      return AudioService.this;
    }
  }

  @Override public int onStartCommand(Intent intent,int flags, int startId) {
    Timber.e("=======onStartCommand=====");
    return super.onStartCommand(intent, flags, startId);
  }

  @Override public void onStart(Intent intent, int startId) {
    super.onStart(intent, startId);
    Timber.e("=======onStart=====");
  }

  @Override public void onDestroy() {
    super.onDestroy();
    Timber.e("=======onDestroy=====");
  }
}
